#include<iostream>
using namespace std;
#include<unistd.h>
#include<stdio.h>
#include<sys/wait.h>
#include<string> 
#include<vector>
#include<time.h>
enum{
   OK=0,
   OPEN_FILE_ERROR,
};
vector<int> data;
int SaveBegin()
{
   string name=to_string(time(nullptr));
   name+=".backup";
   FILE* fp=fopen(name.c_str(),"w");
   if(fp==nullptr)
   {
     return OPEN_FILE_ERROR;
   } 

   string datastr;
   for(auto e:data)
   {
     datastr+=to_string(e);
     datastr+=" ";
   }
   fputs(datastr.c_str(),fp);
   fclose(fp);
   return OK;


}
void Save()
{
  
   pid_t id =fork();
   if(id==0)
   {
     int code =SaveBegin();
     exit(code);
   }
  int status=0;
   pid_t rid=waitpid(id,&status,0);
   if(rid>0)
   {
      int code = WEXITSTATUS(status);
      if(code ==0) printf("备份成功 exit code:%d\n",code);
      else printf("备份失败 exit code：%d\n",code);
   }
   else 
   {
     perror("waitpid");
   }  
}
int main()
{
  
   int cnt =1;
   while(true)
   {
     data.push_back(cnt);
     cnt++;
     sleep(1);

     if(cnt%10==0)
     { 
       cout<<"准备备份"<<endl;
       Save();
     }
     else 
     {
       cout<<"还有"<<cnt%10<<"秒，开始备份"<<endl;
     }
   }

}
